package com.iseastar.guojiang.print;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Message;
import android.provider.Settings;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.iseastar.guojiang.BaseActivity;
import com.iseastar.guojiang.app.AppCache;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.model.BluetoothDeviceBean;
import com.iseastar.guojiang.print.adapter.BluetoothSettingAdapter;
import com.iseastar.guojiang.util.BluetoothUtils;
import com.shouhuobao.station.R;
import com.shouhuobao.take.utils.StringUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;

import droid.frame.view.xlist.SListView;

/**
 * Created by joker on 2017/7/26.
 * 1.进入界面检测蓝牙打开状态，如果打开进行第二步
 * 2.如果打来蓝牙检测之前有没有连接过设备，有就直接进行连接，没有进搜索附近可用设备进行展示
 */
public class BluetoothSettingActivity extends BaseActivity implements View.OnClickListener {

    private ToggleButton mBluetoothStatusTB;
    private TextView mCurrentBluetoothStatusTV;
    private TextView mTipsTV;
    private SListView mListView;
    private BluetoothSettingAdapter mAdapter = null;
    private BluetoothDeviceBean deviceBean = null;
    private BluetoothAdapter bluetoothAdapter = BluetoothAdapter
            .getDefaultAdapter();
    private ArrayList<BluetoothDevice> devicesList = null;// 用于存放已配对蓝牙设备
    private int from = 0;//0 从printfragment进入 1从我的设置界面进入

    @Override
    protected void findViewById() {
        setContentView(R.layout.activity_bluetoothsetting);
        super.findViewById();
        getAppTitle().setCommonTitle("打印机设置");
        mBluetoothStatusTB = (ToggleButton) findViewById(R.id.bluetoothstatusTB);
        mCurrentBluetoothStatusTV = (TextView) findViewById(R.id.currentstatusTV);
        mTipsTV = (TextView) findViewById(R.id.tipsTV);
        mListView = (SListView) findViewById(R.id.listview);
        findViewById(R.id.serachBT).setOnClickListener(this);
        devicesList = new ArrayList<BluetoothDevice>();
        mAdapter = new BluetoothSettingAdapter(devicesList, getContext());
        mListView.setAdapter(mAdapter);
        mBluetoothStatusTB.setOnClickListener(this);
        initIntentFilter();
        from = getIntent().getIntExtra("from", 0);
        //搜索附近可用设备
        BluetoothUtils.serachDevice();
        if (BluetoothUtils.isOpen()) {
            mBluetoothStatusTB.setChecked(true);
            BluetoothDeviceBean bluetoothDeviceBean = AppCache.getBluetoothDeviceBean();
            if (bluetoothDeviceBean != null) {
                //获取蓝牙已绑定设备
                Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
                if (pairedDevices.size() > 0) {
                    for (Iterator<BluetoothDevice> iterator = pairedDevices.iterator(); iterator.hasNext(); ) {
                        BluetoothDevice device = iterator.next();
                        if (device.getAddress().equals(bluetoothDeviceBean.getDeviceAddress()) && device.getName().equals(bluetoothDeviceBean.getDeviceName())) {
                            deviceBean = bluetoothDeviceBean;
                            AppCache.setBluetoothDeviceBean(deviceBean);
                            startService(new Intent(getContext(), BluetoothConnectionService.class));
                            break;
                        } else {
                            AppCache.setBluetoothDeviceBean(null);
                        }
                    }
                }
            }
            mTipsTV.setText("可用设备");
        }
        if (!BluetoothUtils.isOpen()) {
            mBluetoothStatusTB.setChecked(false);
            mTipsTV.setText("可用设备(暂无)");
        }
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final BluetoothDevice bean = (BluetoothDevice) mListView.getAdapter().getItem(position);
                if (bean != null) {
                    showLoadingDialog("正在连接");
                    deviceBean = new BluetoothDeviceBean();
                    deviceBean.setDeviceName(bean.getName());
                    deviceBean.setDeviceAddress(bean.getAddress());
                    AppCache.setBluetoothDeviceBean(deviceBean);
                    startService(new Intent(getContext(), BluetoothConnectionService.class));
                }
            }
        });
        mBluetoothStatusTB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    startActivityForResult(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS), 101);
                } else {
                    BluetoothUtils.closeBluetooth();
                }
            }
        });
    }

    private void initIntentFilter() {
        // 设置广播信息过滤
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        // 注册广播接收器，接收并处理搜索结果
        registerReceiver(receiver, intentFilter);
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MsgID.bluetoothconnectinstatus:
                cancelLoadingDialog();
                int status = (int) msg.obj;
                if (status == 0) {
                    showToast("连接成功");
                    if (deviceBean!=null) {
                        mCurrentBluetoothStatusTV.setText("当前打印机: " + deviceBean.getDeviceName());
                    }
                    if (from == 0) {
                        finish();
                    }
                } else {
                    AppCache.setBluetoothDeviceBean(null);
                    showToast("连接失败");
                    mCurrentBluetoothStatusTV.setText("请选择打印机");
                }
        }
        return super.handleMessage(msg);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.serachBT:
                devicesList.clear();
                mAdapter.getItems().clear();
                mAdapter.notifyDataSetChanged();
                showLoadingDialog("搜索附近设备中");
                //搜索附近可用设备
                BluetoothUtils.serachDevice();
                break;
        }
    }

    /**
     * 蓝牙广播接收器
     */
    private BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                    addBandDevices(device);
                } else {
                    addBandDevices(device);
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
                showLoadingDialog("搜索附近设备中");
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
                    .equals(action)) {//设备搜索完毕
                cancelLoadingDialog();
                mAdapter.setItems(devicesList, true);
                if (mAdapter.getItemsSize() > 0) {
                    mTipsTV.setText("可用设备");
                } else {
                    mTipsTV.setText("可用设备(暂无)");
                }
            }
            if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_ON) {
                    mBluetoothStatusTB.setChecked(true);
                    mListView.setEnabled(true);
//                    mAdapter.setItems(bluetoothUtils.getBoundDevice(), true);
                } else if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF) {
                    mBluetoothStatusTB.setChecked(false);
                    mListView.setEnabled(false);
                    mAdapter.getItems().clear();
                    mAdapter.notifyDataSetChanged();
                    mCurrentBluetoothStatusTV.setText("请打开蓝牙后连接打印机");
                }
            }

        }
    };

    /**
     * 添加蓝牙设备到list集合
     *
     * @param device
     */
    public void addBandDevices(BluetoothDevice device) {
        if (!devicesList.contains(device)) {
            if (!StringUtils.isEmpty(device.getName())) {
                devicesList.add(device);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (BluetoothUtils.isOpen()) {
            mBluetoothStatusTB.setChecked(true);
        } else {
            mBluetoothStatusTB.setChecked(false);
        }
    }

    @Override
    public void finish() {
        setResult(RESULT_OK);
        super.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}
